package com.gift.recommendation.util;

import com.gift.recommendation.modules.admin.dto.PictureReq;
import com.gift.recommendation.modules.admin.dto.PictureRsp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.InetAddress;
import java.nio.file.*;
import java.util.List;

/**
 * @author zzh <2658137258@qq.com>
 * @date 2023/2/20
 */
@Component
@Slf4j
public class FileUpLoadUtils {

    @Value("${uploadImg}")
    private String uploadPathImg;
    @Value("${server.port}")
    private String serverPort;

    public PictureRsp uploadImg(MultipartFile file){
        String fileName = "";
        try {
            if (file != null) {
                fileName = file.getOriginalFilename();
                String suffix = null;
                if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
                    suffix = "." + fileName.substring(fileName.lastIndexOf(".") + 1);
                }
                fileName = System.currentTimeMillis() + suffix;
                String uploadFileDir=uploadPathImg;
                File uploadFileDirFile = new File(uploadFileDir);
                if (!uploadFileDirFile.exists())
                {
                    uploadFileDirFile.mkdirs();
                }
                File targetFile = new File(uploadFileDirFile, fileName);
                file.transferTo(targetFile);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        PictureRsp pictureRsp = new PictureRsp();
        InetAddress localHost = null;
        try {
            localHost = InetAddress.getLocalHost();
        }catch (Exception e){
            throw new RuntimeException("获取IP地址失败");
        }
        String ip = localHost.getHostAddress();
        String port = serverPort;
        pictureRsp.setPictureUrl("http://" + ip + ":" + port + "/uploadImg/" + fileName);
        pictureRsp.setPictureName(fileName);
        return pictureRsp;
    }

    public void deleteImg (PictureReq req) {
        if (CollectionUtils.isNotEmpty(req.getPictureName())) {
            req.getPictureName().forEach(fileName -> {
                Path fileDir = Paths.get(uploadPathImg + fileName);
                try {
                    Files.delete(fileDir);
                }catch (NoSuchFileException e) {
                    log.error("文件不存在,直接删除");
                }catch (DirectoryNotEmptyException e) {
                    throw new RuntimeException("删除非空目录");
                }catch (FileSystemException e) {
                    throw new RuntimeException("删除被占用文件");
                }catch (Exception e) {
                    throw new RuntimeException("未知原因,无法删除");
                }
            });
        }
    }

}
